<template>
  <div :class="{'theme-market': showMarketingBar}">
    <section class="c-maxh427 c-text-hidden c-p">
      <img class="c-w100" :src="$addXossFilter(testInfo.avatar, require('../../../assets/defult270.png'))" alt="" />
    </section>
    <!-- 营销活动倒计时 -->
    <flash-sales-time-new v-if="showMarketingBar"
      :type="testInfo.sales? 'isSale':testInfo.isFriendHelper ? 'isFa' : testInfo.bargain ? 'isBargain' : 'isCollage'"
      :price="testInfo.bargain ? testInfo.bargain.reservePrice : testInfo.sales ? testInfo.sales.price : testInfo.collage ? testInfo.collage.captainPrice : ''"
      :from="testInfo.collage && testInfo.collage.collageGroupType && testInfo.collage.collageGroupType == 2 ? 'activity' : ''"
      :startTime="testInfo.bargain ? testInfo.bargain.startTime : testInfo.sales ? testInfo.sales.sales.startTime : testInfo.collage ? testInfo.collage.startTime : testInfo.faStartAt"
      :endTime="testInfo.bargain ? testInfo.bargain.endTime : testInfo.sales ? testInfo.sales.sales.endTime : testInfo.collage ? testInfo.collage.endTime : testInfo.faEndAt"
      :originalPrice="testInfo.price"
      :stockBargain="testInfo.bargain && testInfo.bargain.stock"
      :bargainStatus="testInfo.bargain && testInfo.bargain.status"
      :isPreheat="testInfo.bargain && testInfo.bargain.isPreheat"
      :stock="testInfo.sales ? testInfo.sales.balance: ''"
      :isLimit="testInfo.sales && testInfo.sales.limit == 0 || (testInfo.bargain && testInfo.bargain.isLimitStock == 2) ? false : true"
      :salesTag="testInfo.sales && testInfo.sales.sales.tags"
      :peopleNum="testInfo.collage && testInfo.collage.peopleNum"
      :optimal="optimal"
      @showCoupon="showCoupon = true"
      @falshSalesTime="falshSalesTime"
      @finishFlashSales="finishFlashSales"
    ></flash-sales-time-new>
    <section class="c-p" v-if="testInfo != ''">
      <div class="c-bd-b12-f5 c-mt24">
        <price-bar v-if="testInfo.isSaleAlone==1&& !testInfo.permission&&!(testInfo.sales|| (testInfo.collage && (testInfo.collage.status == 2 || testInfo.collage.status == 1)) ||testInfo.isFriendHelper)"
          :dataInfo="testInfo"
          :styleType="2"
        >
        </price-bar>
        <discount-info class="c-mt8" v-if="!distributionId && !isiOS && !testInfo.permission && testInfo.isSaleAlone == 1 && testInfo.payType == 2"
          :couponList="couponList"
          :dataInfo="testInfo"
          :isMarketing="isMarketing"
          @clickShowCoupon="showCoupon = true"
        >
        </discount-info>
        <vip-entry class="c-ph24 c-mt20"
          :vipDiscount="testInfo.vipDiscount"
          :svipDiscount="testInfo.svipDiscount"
          :originPrice="Number(testInfo.price)"
          :vipDiscountPrice="Number(testInfo.vipDiscountPrice)"
          :svipDiscountPrice="Number(testInfo.svipDiscountPrice)"
          :styleType="2"
          :vipDiscountType="testInfo.vipDiscountType"
          :dataInfo="testInfo"
          v-if="!testInfo.permission && !$isWxAppIos() && !isiOS && !isMarketing"
        ></vip-entry>
        <div class="c-ph24 c-mt24">
          <div class="c-fs30 c-fc-xblack c-fw600">{{testInfo.name}}</div>
        </div>
        <div class="c-ph24 c-flex-row c-justify-sb c-pt20 c-alignc-center" v-if="testInfo.desc">
          <span class="c-fs22 c-fc-gray c-flex-1 c-mr50">{{testInfo.desc}}</span>
        </div>
        <div class="c-ph24 c-pb20 c-flex-row c-justify-sb c-pt20 c-aligni-center">
          <div class="c-fs22 c-fc-gray c-flex-row c-aligni-center">
            <div class="c-flex-row c-aligni-center">
              <div class="icon iconfont">&#xe792;</div>
              含{{testInfo.questionNum}}题
            </div>
            <div class="c-flex-row c-aligni-center c-ml16">
              <div class="icon iconfont c-fs18 c-mr4">&#xe69c;</div>
              {{testInfo.subscribers}}人参与
            </div>
          </div>
        </div>
      </div>
      <bargain-rules
        v-if="testInfo.bargain != null && !testInfo.permission"
        :isPreheat="testInfo.bargain.isPreheat"
        :status="testInfo.bargain.status"
        class="c-bd-t12-f5"
      ></bargain-rules>
      <collage-persons-list v-if="testInfo && !testInfo.permission && testInfo.collage != null && (testInfo.collage.status == 2 || testInfo.collage.status == 1)" class="c-bd-b12-f5" :collage="testInfo.collage" @goCollageDetail="gcd"></collage-persons-list>
    </section>
    <div class="c-hh76" id="tabhBar">
      <my-small-tabbar class="c-bg-white c-hh76 c-bd-b1-f6 c-ph24" :styleType="2" :class="tabhBarFixed == true ? isiOS ? 'tab-bar-ios' : ($isWxApp() ? 'tabhBar c-wx-top0' : 'tabhBar')  : ''" :tabList="tabList" :tabIndex="typeBar" @changeTab="changeType"></my-small-tabbar>
    </div>
    <div class="c-pt24 c-pb120 c-fc-sblack c-fs26">
      <div @click="clickDesc" class="tinymce-text c-ww-bw c-ww-ba c-contexty-scroll c-ph24" :class="[cfg.isCopyPicture == 0 ? 'closeBig' : 'aCloseBig', cfg.isCopy == 0 ? 'copyNot' : '']" v-html="testInfo.detail"></div>
      <loading-status-tem :noData="testInfo.detail == ''" :noDataText="'暂无内容'"></loading-status-tem>
      <package-index-com :styleType="2"
        @clickGoAllPackage="showCombo=true"
        :relevantTitles="'包含该练习的课程'"
        :isExam='cfrom.itemBank' :showAll="true"
        :proType="9" :proId="libraryId"
        :isHomePage="false"
        :showPackageModal="true"
        :packageList="testInfo.combos.filter((item,index) => {return index == 0})"
        v-if="testInfo && testInfo.combos && testInfo.combos.length > 0"></package-index-com>
    </div>
    <bottom-buy-com
      :ckFrom="cfrom.itemBank"
      :isNeedPay="!testInfo.permission && ((testInfo.isSaleAlone == 1 && testInfo.payType == 2) || (testInfo.isSaleAlone != 1 && testInfo.isSaleTogether == 1))"
      :showInvitionCard="false"
      :showMarketingCard="testInfo.isFriendHelper || testInfo.bargain || (testInfo.collage && (testInfo.collage.status == 2 || testInfo.collage.status == 1)) || testInfo.sales"
      :showFriendHelper="testInfo.permission == 0 && companyAuth.enableFriendHelper == 1 && testInfo.isFriendHelper"
      :showBuyPackage='testInfo.isSaleAlone == 0 && testInfo.status != 3 && testInfo.permission == 0'
      :showBuyButton="testInfo.payType != 3 && testInfo.status != 3 && testInfo.permission == 0 && testInfo.payType == 2"
      @spreadInvite="spreadInvite"
      :friendHelperStatus="faStatus"
      @goHelpDetail="goHelpDetail"
      @invitePoster="invitePoster"
      @backPackage="backPackage"
      :showFormText="0"
    >
      <div class=" c-hh64 c-fs28" v-if="testInfo.isSaleAlone==1" :class="testInfo.collage && (testInfo.collage.status == 2 || testInfo.collage.status == 1) && testInfo.collage.userType != -1 ? '' : 'c-w0 c-flex-grow1'">
        <!-- 付费 -->
        <div v-if="!testInfo.permission && testInfo.payType == 2" class="c-flex-row c-flex-center c-br36 c-fs24" :class="testInfo.isFriendHelper || (testInfo.collage && (testInfo.collage.status == 2 || testInfo.collage.status == 1)) ? '' : 'c-flex-grow1'">
          <div @click="takePartIn" v-if="testInfo.enableExperience == 1" class="c-bg-white theme-bd1 theme-fc c-lh c-ww160 c-flex-row c-flex-center c-hh64 c-br36 c-fs28 c-mr40">免费体验</div>
          <div @click="clickBuy" v-if="!((testInfo.collage && (testInfo.collage.status == 2 || testInfo.collage.status == 1)) || testInfo.bargain)" class="theme-bg c-fc-white c-lh c-flex-grow1 c-flex-row c-flex-center c-hh64 c-br36 c-fs28">{{getBuyBtnTitle}}</div>
          <div v-if="testInfo.collage && (testInfo.collage.status == 2 || testInfo.collage.status == 1) && testInfo.collage.userType != -1" class="c-pv16 c-fs24 theme-fc c-ph40 c-br36 c-textAlign-r" @click="goCollageDetail(testInfo.collage.groupId,testInfo.collage.collageId)">
            拼团中...
          </div>
          <div class="c-flex-row c-hh64 c-flex-grow1" v-if="testInfo.collage && (testInfo.collage.status == 2 || testInfo.collage.status == 1) && testInfo.collage.userType == -1">
            <div class="c-flex-column c-aligni-center c-flex-grow1 theme-fc c-justify-sa theme-bd1 c-br32 c-mr10 c-ml16" @click="clickBuy">
              <span class="c-fs22 c-lh">{{'￥' | iosPriceFilter('Live')}}{{calculationPrice}}</span>
              <span class="c-fs20 c-lh">{{getBuyBtnTitle}}</span>
            </div>
            <div class="c-flex-column c-aligni-center c-flex-grow1 c-fc-white c-justify-sa c-br32" :class="testInfo.collage.status == 2 ? 'theme-bg-gradient' : 'c-bg-d7'" @click="goBuy(-1,testInfo.collage.collageId)">
              <span class="c-fs22 c-lh">{{'￥' | iosPriceFilter('Live')}}{{Number(testInfo.collage.captainPrice).toFixed(2)}}</span>
              <span class="c-fs20 c-lh">发起拼团</span>
            </div>
          </div>
          <!-- 砍价信息不为空 -->
          <div class="c-flex-row c-w100 c-hh64 c-flex-center" v-if="testInfo.bargain != null && ((testInfo.bargain.status == 1 && testInfo.bargain.isPreheat == 1) || testInfo.bargain.status == 2)">
            <div class="c-flex-column c-justify-sa c-aligni-center theme-fc c-hh64 theme-bd1 c-w50 c-br32 c-mr10" @click="clickBuy">
              <span class="c-fs22 c-lh">{{'￥' | iosPriceFilter}}{{calculationPrice}}</span>
              <span class="c-fs20 c-lh">{{getBuyBtnTitle}}</span>
            </div>
            <!-- 未发起砍价 -->
            <template v-if="testInfo.bargain.userType == 1">
              <div class="c-flex-row c-flex-center c-fc-white c-hh64 c-w50 c-fs28 c-br32 theme-bg-gradient" @click="handleClickBargainDetail(testInfo.bargain.bargainId)">正在砍价</div>
            </template>
            <template v-if="testInfo.bargain.userType == -1">
              <div class="c-flex-column c-justify-sa c-aligni-center c-fc-white c-hh64 c-w50 c-br32" :class="(testInfo.bargain.status == 1 && testInfo.bargain.isPreheat == 1) ? 'c-bg-d7' : 'theme-bg-gradient'" @click="handleClickBargainDetail(testInfo.bargain.bargainId)">
                <span class="c-fs22 c-lh">{{'￥' | iosPriceFilter}}{{Number(testInfo.bargain.reservePrice).toFixed(2)}}</span>
                <span class="c-fs20 c-lh">砍价享</span>
              </div>
            </template>
          </div>
        </div>
        <!-- 加密 -->
        <div @click="inputPsw" v-if="testInfo.permission == false && testInfo.payType == 3" class="c-fc-white theme-bg c-br36 c-h c-flex-row c-flex-center">输入密码</div>
        <!-- 有权限 -->
        <div v-if="testInfo.permission" class="c-fc-white c-lh c-flex-row c-flex-center c-h c-br36 theme-bg" @click="goTest">开始练习</div>
      </div>
      <div @click="takePartIn" v-if="testInfo.isSaleAlone==-1&testInfo.isSaleTogether==1&&testInfo.enableExperience == 1&&testInfo.permission == false" class="c-bg-white theme-bd1 theme-fc c-lh c-ww160 c-flex-row c-flex-center c-hh64 c-br36 c-fs28 c-mr40">免费体验</div>
      <div class="c-w0 c-hh64 c-flex-grow1 c-fs28" v-if="testInfo.isSaleAlone==-1&testInfo.isSaleTogether==1">
        <div v-if="testInfo.permission == false " class="c-fc-white c-lh c-flex-row c-flex-center c-h c-br36 theme-bg" @click="showCombo=true">立即购买</div>
        <div v-if="testInfo.permission" class="c-fc-white c-lh c-flex-row c-flex-center c-h c-br36 theme-bg" @click="goTest">
          {{testInfo.hasStart==2?'查看成绩':'开始练习'}}
        </div>
      </div>
    </bottom-buy-com>
    <coupon-list-com
      @closeModal="closeModal"
      @getCouponList="getCouponList"
      :couponIsPage="couponIsPage"
      :couponLoading="couponLoading"
      :couponList="couponList"
      :showCoupon="showCoupon"
      :prodId="Number(libraryId)"
      :prodType="cfrom.itemBank"
      :sales="testInfo.sales"
      :collage="testInfo.collage"
      :isMarketing="isMarketing"
      :dataInfo="testInfo"
    ></coupon-list-com>
    <comfirm-com :pwTip="testInfo.passwordTip ? testInfo.passwordTip : ''" :showPassword="showPassword" :noticeText="noticeText" :text="'请输入密码进入测试'" :placeholderText="'请输入密码'" @changePsw="changePsw" @closePassword="showPassword = false" @submitPassword="submitPassword"></comfirm-com>
    <share-masker :isShowShare="isShowShare" v-if="isShowShare" @closeShare="isShowShare=false;"></share-masker>
    <!-- 关注二维码 -->
    <offical-account
      v-if="testInfo && testInfo.bargain"
      :showAccountQcode="showAccountQcode"
      :desc="officalDesc"
      :imgSrc="$addXossFilter(mpQrcode)"
      @hideDialog="hideDialog"
    ></offical-account>
    <!-- 关联弹窗 -->
    <combo-related-list :tittle="'包含该练习的课程'" :minTittle="'购买所属的课程后可参与练习'" :packageList="packageList" @closeCombo="closeCombo" :showCombo="showCombo"></combo-related-list>
    <collage-grades ref="collageGrades" :relType='11' :refereeId="refereeId" :isRelForm="testInfo.isRelForm && !testInfo.hasFormLog" :extId="testInfo.libraryId" :bindPhoneSetting="bindPhoneSetting" :goodsRoomId="goodsRoomId" :dataInfo="testInfo"></collage-grades>
  </div>
</template>
<script>
import shareMasker from "@/components/templates/common/shareMasker.vue";
import PackageIndexCom from "@/components/templates/packageIndexCom.vue";
import ComfirmCom from "@/components/templates/common/comfirmCom.vue";
import couponListCom from "@/components/templates/couponListCom.vue";
import { utilJs, wxUtilJs } from "@/utils/common.js";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import bottomBuyCom from "@/components/templates/common/bottomBuyCom.vue";
import FlashSalesTimeNew from "@/components/templates/flashSalesTimeNew.vue";
import CollagePersonsList from "@/components/templates/collage/collagePersonsList.vue";
import PriceBar from '@/components/templates/common/priceBar.vue';
import bargainRules from '@/components/templates/bargain/bargainRules';
import officalAccount from '@/components/templates/common/officalAccount';
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
// import ElTreeSelect from "@/components/templates/tree.vue";
import { getBindPhoneSetting } from "@/utils/checkUnBindPhone.js";
import DiscountInfo from "@/components/templates/common/discountInfo.vue";
import VipEntry from "@/components/templates/common/vipEntry.vue";
import ComboRelatedList from "@/components/templates/common/comboRelatedList.vue";
import collageGrades from "@/components/templates/collage/collageGrades.vue";
// let libraryId = "";
let isClick = false;
let pathFrom = '';
export default {
  name: "ClassDetail",
  components: {
    MySmallTabbar,
    shareMasker,
    PackageIndexCom,
    ComfirmCom,
    ComboRelatedList,
    couponListCom,
    bottomBuyCom,
    loadingStatusTem,
    FlashSalesTimeNew,
    CollagePersonsList,
    PriceBar,
    bargainRules,
    officalAccount,
    DiscountInfo,
    VipEntry,
    collageGrades
    // ElTreeSelect
  },
  data() {
    return {
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      testInfo: {}, //permission是否有权限
      vipType: localStorage.getItem("vipType" + localStorage.getItem("userId")),
      vipFitstItem: localStorage.getItem("vipArr1") ? JSON.parse(localStorage.getItem("vipArr1")) : null,
      svipFitstItem: localStorage.getItem("svipArr1") ? JSON.parse(localStorage.getItem("svipArr1")) : null,
      cfg: JSON.parse(localStorage.getItem("cfg")),
      isiOS: false,
      couponLoading: false,
      couponList: [],
      couponIsPage: false,
      couponPage: 1,
      comboId: '',
      ttId: "",
      tpId: "",
      tlId: "",
      progress: "",
      showCoupon: false,
      isSalesBegin: false, // 判断限时购正在进行
      packageList: [],
      libraryId: '',
      showPassword: false, //显示密码输入
      noticeText: '',
      faStatus: 0,
      cfrom: global.ckFrom,
      isShowShare: false, //目前分享邀请功能未有
      showAccountQcode: false,
      officalDesc: '关注我们后才可发起砍价哦',
      mpQrcode: '',
      dataStatus:'HAS_MORE_DATA',
      trainDataStatus:'HAS_MORE_DATA',
      is_page_package: false,
      pagePackage:1,
      belongLoading:false,
      showCombo:false,
      bindPhoneSetting: null,
      themeId: '', //来源圈子任务的主题id
      tabList: [{
        title: '详情',
        index: 0,
      }],
      typeBar:0,
      optimal: null, // 最低价格对象
    };
  },
  created() {
    utilJs.appShare(this);
    let reIdArr = window.location.href.split("libraryId=");
    if (reIdArr.length > 1 && reIdArr[1]) {
      let rId = reIdArr[1].split("&").length > 0 ? reIdArr[1].split("&")[0] : reIdArr[1];
      window.localStorage.setItem("libraryId", rId);
    }
  },
  mounted() {},
  beforeRouteEnter(to, from, next) {
    next(vm => {
      pathFrom = from.path;
    });
  },
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      window.location.reload(true)
    }
  },
  computed: {
    showMarketingBar() {
      return this.testInfo && !this.testInfo.permission &&
        (
          this.testInfo.sales ||
          (this.testInfo.collage && (this.testInfo.collage.status == 2 || this.testInfo.collage.status == 1)) ||
          this.testInfo.isFriendHelper ||
          (this.testInfo.bargain && ((this.testInfo.bargain.status == 1 && this.testInfo.bargain.isPreheat == 1) || this.testInfo.bargain.status == 2))
        )
    },
    // 获取按钮专享价名称
    getBuyBtnTitle() {
      if (this.optimal) {
        const agentName = utilJs.getCustNameMap();
        let btnTxt = '立即购买';
        let idDiscount = (this.vipType == 3 || this.vipType > 4) && this.testInfo.commonProdInfo && this.testInfo.commonProdInfo.agentDiscount < 100
          ? this.testInfo.commonProdInfo.agentDiscount
          : (this.vipType == 4 && this.testInfo.svipDiscount < 100)
            ? this.testInfo.svipDiscount
            : (this.vipType == 2 && this.testInfo.vipDiscount < 100)
              ? this.testInfo.vipDiscount
              : 100
        let discountPrice = Number(this.testInfo.price * idDiscount / 100).toFixed(2);
        btnTxt = discountPrice * 1 != this.testInfo.price ? (this.vipType != 1 ? (this.vipType == 2 ? 'VIP专享价' : this.vipType == 4 ? 'SVIP专享价' : agentName[this.vipType] + '专享价') : '立即购买') : '立即购买';
        if (this.testInfo.sales && this.optimal.optimalPriceType == 101) {
          btnTxt = '立即购买';
        }
        return btnTxt
      }
      return '立即购买'
    },
    //营销原价计算价格
    calculationPrice() {
      let idDiscount = (this.vipType == 3 || this.vipType > 4) && this.testInfo.commonProdInfo && this.testInfo.commonProdInfo.agentDiscount < 100
          ? this.testInfo.commonProdInfo.agentDiscount
          : (this.vipType == 4 && this.testInfo.svipDiscount < 100)
            ? this.testInfo.svipDiscount
            : (this.vipType == 2 && this.testInfo.vipDiscount < 100)
              ? this.testInfo.vipDiscount
              : 100
      let calculationPrice = Number(this.testInfo.price * idDiscount / 100).toFixed(2)
      return calculationPrice;
    },
    //是否是营销活动
    isMarketing() {
      let isMarketing = this.testInfo &&
      (this.testInfo.sales || (this.testInfo.bargain && ((this.testInfo.bargain.status == 1 && this.testInfo.bargain.isPreheat == 1) || this.testInfo.bargain.status == 2)) ||
      (this.testInfo.collage &&
      (this.testInfo.collage.status == 2 || this.testInfo.collage.status == 1)) || this.testInfo.isFriendHelper)
      return isMarketing
    },
    //单卖&&没有权限&&价格大于0&&（加入形式&&不是好友助力）&&（优惠券||vip svip折扣信息||积分抵扣）&&（是否参与营销）
    showDiscount() {
      let showdiscount = this.testInfo.isSaleAlone != 0 && this.testInfo.permission == false && Number(this.testInfo.price) > 0 && !this.testInfo.isFriendHelper
      return showdiscount
    },
  },
  watch: {},
  methods: {
    changeType: function (type, changeDir) {
      //this.typeBar = typeBar;
      return false;
    },
    closeCombo() {
      this.showCombo = false;
    },
    clickPackageItem(packageId) {
      this.$routerGo(this, "push", {
        path: "/homePage/package/packageDetail",
        query: { combosId: packageId }
      });
    },
    clickTrainItem(subId) {
      this.$routerGo(this, "push", {
        path: "/homePage/camp/campDetail",
        query: {
          campId: subId,
          ckFrom: global.ckFrom.camp
        }
      });
    },
    takePartIn() {
      let $this = this;
      let data = {
        libraryId: this.libraryId,
        type: 1,
      };
      utilJs.postMethod(`${global.apiurl}itemBank/takePartIn`, data, function (
        res
      ) {
        let queryT = {
          libraryId: $this.libraryId,
          type: 1,
          goOnNum: 1,
          isExperience: 1,
          exNum: $this.testInfo.exNum
        }
        if ($this.testInfo.sales && $this.testInfo.sales.sales.status == 2) {
          queryT.pId = $this.testInfo.sales.pId;
        }
        $this.$routerGo($this, "push", {
          path: '/homePage/itemBank/questionAnswer',
          query: queryT
        })
      })
    },
    hideDialog() {
      this.showAccountQcode = false;
    },
    falshSalesTime(status) {
      if (this.testInfo.bargain) {
        this.testInfo.bargain.status = status;
      }
    },
    finishFlashSales(status) {
      if (this.testInfo.bargain) {
        this.getTestDetail();
      }
    },
    // 判断是否关注公众号
    checkUserIsFollowedMp() {
      let _this = this;
      return new Promise(function (resolve, reject) {
        utilJs.getMethod(`${global.apiurl}bargains/getMpData?bargainId=${_this.testInfo.bargain.bargainId}`,
          res => {
            resolve(res);
          },
          failRes => {
            reject(failRes)
          }
        )
      })
    },
    // 砍价
    handleClickBargainDetail(bargainId) {
      if (this.testInfo.bargain.status == 1) {
        this.$showCjToast({
          text: '活动未开始，暂不能砍价！',
          type: 'warn'
        });
        return;
      }
      this.checkUserIsFollowedMp().then(res => {
        if (res.threshold == 2 && res.isFollowedMp == 0) {
          this.mpQrcode = res.mpQrcode;
          this.showAccountQcode = true;
          return;
        }
        // 判断是否绑定手机号
        if (this.bindPhoneSetting && this.bindPhoneSetting.buyBind) {
          if (utilJs.goBindMobile()) return;
        }
        if (this.testInfo.collectPage == 1 && this.testInfo.isRelForm == true && this.testInfo.hasFormLog == false && localStorage.getItem("showForm") == 1) {
          this.goForm(bargainId);
          return;
        }
        if (this.testInfo.bargain.status == 2) {
          this.$routerGo(this, "push", {
            path: "/homePage/bargain/bargainDetail",
            query: {
              bargainId: bargainId
            }
          });
        }
      })
    },
    //提交密码
    submitPassword(inputPwd) {
      if (isClick) {
        return;
      }
      isClick = true;
      utilJs.postMethod(global.apiurl + "paper/passwordJoin", {
        password: inputPwd,
        type: 3,
        prodId: this.libraryId
      }, res => {
        isClick = false;
        if (res.code == 500) {
          this.noticeText = "*密码错误";
        } else if (res.code == 200) {
          this.showPassword = false;
          this.goTest()
        }
      },
        failRes => {
          isClick = false;
        }
      );
    },
    changePsw() {
      this.noticeText = "";
    },
    inputPsw() {
      if (this.bindPhoneSetting && this.bindPhoneSetting.passwordBind) {
        if (utilJs.goBindMobile()) return;
      }
      this.noticeText = "";
      this.showPassword = true;
    },
    getRelatePackage(tabType) {
      if (!this.belongLoading) {
        this.belongLoading = true;
        let $this = this;
        // if (tabType == 2) {+ '&page=' + this.pagePackage + '&limit=10' + '&tabType=' + tabType
          let getUrl = `${global.apiurl}common/saleTogetherList`;
          utilJs.getMethod(getUrl + "?prodId=" + $this.libraryId + '&prodType=' + global.ckFrom.itemBank, function (res) {
            $this.belongLoading = false;
            $this.packageList = res
            // if ($this.pagePackage == 1) { //从课程刚进来页面的时候需要获取专栏列表，第二页开始不需要了
            //   $this.packageList = res.list.combos.data;
            // }
            // $this.pagePackage = res.list.combos.current_page < res.list.combos.last_page ? ($this.pagePackage + 1) : $this.pagePackage;
            // $this.is_page_package = res.list.combos.current_page < res.list.combos.last_page ? true : false;
          }, failRes => {
            $this.belongLoading = false;
          });
        // }
      }
    },
    clickDesc(e) {
      if (e.target.tagName == 'IMG' && e.target.src) {
        wxUtilJs.previewImage({
          current: e.target.src, // 当前显示图片的http链接
          urls: [e.target.src] // 需要预览的图片http链接列表
        });
      }
    },
    goTest() {
      if (this.bindPhoneSetting && this.bindPhoneSetting.getBind) {
        if (utilJs.goBindMobile()) return;
      }
      if (this.testInfo.isRelForm == true && this.testInfo.hasFormLog == false && localStorage.getItem("showForm") == 1) {
        this.goForm('');
        return
      }
      if (this.testInfo.questionNum == 0) {
        this.$showCjToast({
          text: '该练习无题目',
          type: "warn",
          time: 1500
        });
      }
      if (this.testInfo.hasJoinRecord == false) {
        utilJs.postMethod(global.apiurl + "itemBank/joinFreeItemBank", {
          libraryId: this.libraryId,
          trainId: this.ttId,
          comboId: this.comboId
        },
        res => {
          if (res.code == 200) {
            this.$routerGo(this, "push", {
              path: '/homePage/itemBank/practiceModes',
              query: {
                practiceId: this.libraryId,
                ttId: this.ttId,
                tpId: this.tpId,
                tlId: this.tlId,
                progress: this.progress,
              }
            })
          } else {
            this.$showCjToast({
              text: res.msg,
              type: "warn",
              time: 1500
            });
          }
        },
      )
      } else {
        this.$routerGo(this, "push", {
          path: '/homePage/itemBank/practiceModes',
          query: {
            practiceId: this.libraryId,
            ttId: this.ttId,
            tpId: this.tpId,
            tlId: this.tlId,
            progress: this.progress,
          }
        })
      }
    },
    closeModal() {
      this.showCoupon = false;
    },
    //获取可以领取的优惠券
    getCouponList: function () {
      if (!this.couponLoading) {
        this.couponLoading = true;
        let $this = this;
        utilJs.getMethod(global.apiurl + 'redeemCodes/getCouponsByRedeemType?courseId=' + $this.libraryId + '&redeemType=141&limit=10&page=' + this.couponPage, function (res) {
          $this.couponLoading = false;
          $this.couponList = $this.couponList.concat(res.data);
          $this.couponPage = res.next_page_url ? ($this.couponPage + 1) : $this.couponPage;
          $this.couponIsPage = res.next_page_url ? true : false;
        },
          failRes => {
            $this.couponLoading = false;
          }
        );
      }
    },
    //回退到上级(知识套餐),不支持单独售卖
    backPackage: function () {
      if (pathFrom == "/homePage/column/columnDetail" || pathFrom == "/homePage/package/packageDetail") {
        this.$router.go(-1);
      } else {
        this.$routerGo(this, "push", {
          path: "/homePage/package/packageList",
          query: { noHighL: true, 'showAll': true, 'proType': 8, "proId": this.libraryId }
        });
      }
    },
    //助力详情
    goHelpDetail: function () {
      if (this.bindPhoneSetting && this.bindPhoneSetting.helpBind && utilJs.goBindMobile()) {
       return
      }
      if (this.faStatus == 1) {
        this.$showCjToast({
          text: '活动未开始，暂不能助力领取！',
          type: 'warn'
        });
      } else {
        this.$routerGo(this, "push", {
          path: "/homePage/task/task",
          query: { 'faId': this.testInfo.faId, 'refereeId': localStorage.getItem("userId") }
        });
      }
    },
    //活动海报
    invitePoster: function () {
      if (this.bindPhoneSetting && this.bindPhoneSetting.shareBind) {
        if (utilJs.goBindMobile()) return;
      }
      let ckFrom = this.cfrom.itemBank;//this.ckFrom;
      let type = this.testInfo.collage ? 3 : this.testInfo.sales ? 2 : this.testInfo.bargain ? 5 : 4;
      let cId = this.testInfo.isFriendHelper ? this.testInfo.faId : this.testInfo.collage ? this.testInfo.collage.collageId : this.testInfo.bargain ? this.testInfo.bargain.bargainId : this.testInfo.sales.pId;
      let proId = this.libraryId;
      this.$routerGo(this, "push", { path: '/homePage/spread/spreadPoster', query: { cId: cId, type: type, ckFrom: ckFrom, proId: proId } });
    },
    //邀请好友
    spreadInvite() {
      if (this.bindPhoneSetting && this.bindPhoneSetting.shareBind) {
        if (utilJs.goBindMobile()) return;
      }
      if (this.testInfo.isInvitionCard == 0) {
        this.isShowShare = true;
        return;
      }
      let extId = this.$route.query.libraryId;
      this.$routerGo(this, "push", {
        path: "/homePage/spread/spreadCustom",
        query: {
          ckFrom: this.cfrom.itemBank,
          cId: 0,
          extId: extId
        }
      })
    },
    //获取详情
    getTestDetail() {
      let postUrl = global.apiurl + "itemBank/itemBankInfo/" + this.libraryId;
      if (this.themeId) {
        postUrl = postUrl + `&themeId=${this.themeId}`
      }
      utilJs.getMethod(postUrl,
        res => {
          if (res.status == -1) {
            this.$routerGo(this, "replace", {
              path: "/error/emptyPage",
              query: {
                info: "很抱歉，该练习不存在"
              }
            });
          }
          if ((res.price * 1 > 0 && res.status == 0 && !res.permission) || (res.price * 1 == 0 && res.status == 0)) {
            this.$routerGo(this, "replace", {
              path: "/error/emptyPage",
              query: {
                info: '很抱歉，该练习已下架'
              }
            })
          }
          if (res.collage != null && this.companyAuth.enableCollage == 1) {
            let nt = (new Date()).getTime();
            let st = utilJs.getTimeByDate(res.collage.startTime);
            let et = utilJs.getTimeByDate(res.collage.endTime);
            if (nt >= st && nt < et && res.collage.status < 3) {
                // this.ckFrom = res.columnId == 0 ? global.ckFrom.collageCourse : global.ckFrom.collageColumn;
              res.collage.status = 2;
            } else if (nt < st && res.collage.status == 1) {
                // $this.ckFrom = res.columnId == 0 ? global.ckFrom.collageCourse : global.ckFrom.collageColumn;
              res.collage.status = 1;
            } else if (nt >= et && res.collage.status == 2) {
              res.collage.status = 3;
              res.collage = null;
                // $this.ckFrom = res.columnId == 0 ? global.ckFrom.course : global.ckFrom.column;
            } else {
              res.collage = null;
                // $this.ckFrom = res.columnId == 0 ? global.ckFrom.course : global.ckFrom.column;
            }
          } else if (res.sales != null && (res.sales.limit == 0 || res.sales.balance > 0) && res.sales.status && this.companyAuth.enableFlashSalesModule == 1) { // 限时购
            let nt = (new Date()).getTime();
            let st = utilJs.getTimeByDate(res.sales.sales.startTime);
            let et = utilJs.getTimeByDate(res.sales.sales.endTime);
            if (nt >= st && nt < et && res.sales.sales.status > -1) {
              res.sales.sales.status = 2;
            } else if (nt < st && res.sales.sales.status == 1) {
              res.sales.sales.status = 1;
              // $this.dataInfo.sales = null;
            } else if (nt >= et && res.sales.sales.status == 2) {
              res.sales.sales.status = -1;
              res.sales = null;
            } else {
              res.sales = null;
            }
          } else {
            res.collage = null;
            res.sales = null;
          }
          res.isFriendHelper = false;
          this.testInfo = res
          // optimalPriceType：1 产品本身价格 2 vip价格 3 svip价格 4 服务商 101 限时购 102 拼团 112 砍价  10 链动会员 20 链动代理商 99 链动复购
          this.optimal = res.optimal || null;
          this.wechatShare();
          this.getRelatePackage()
          if (res.sales && res.sales.sales) {
            this.isSalesBegin = (res.sales.sales.startTime).replace(/\s+|[-]|[:]/g, "") <= (utilJs.getNowTime()).replace(/\s+|[-]|[:]/g, "") ? true : false;
          }
        }
      );
    }, //表单
    goForm(bargainId) {
      let isGoBack = this.testInfo.permission ? 1 : 0;
      let queryT = null;
      let pId = this.testInfo.sales ? this.testInfo.sales.pId : null;
      queryT = {
        extId: this.testInfo.paperMainId,
        ckFrom: this.cfrom.testpPaper,
        isFromInvite: 0,
        cId: -1,
        pId: pId,
        isGoBack: isGoBack,
        type: 1,
        relType: 11,
        bargainId: bargainId
      }
      this.$routerGo(this, "push", { path: '/homePage/form', query: queryT });
    },
    gcd: function (cinfo) {
      this.goCollageDetail(cinfo.groupId, cinfo.collageId);
    },
    //拼团详情
    goCollageDetail: function (groupId, collageId) {
      if (this.testInfo.collage.userType != -1 && this.testInfo.collage.groupId != groupId) {
        this.$showCjToast({
          text: '您已在拼团中，不需要再去拼单啦！',
          type: 'warn'
        });
      } else {
        if (this.testInfo.collage.status == 1) {
          this.$showCjToast({
            text: '活动未开始，暂不能拼团！',
            type: 'warn'
          });
        } else {
          let hfs = this.testInfo.isRelForm && !this.testInfo.hasFormLog;
          let pathQuery = {
            'groupId': groupId,
            'collageId': collageId,
            isRelForm: hfs,
            extId: this.testInfo.libraryId,
          };
          this.$routerGo(this, "push", {
            path: "/homePage/collage/collageDetail",
            query: pathQuery
          });
        }
      }
    },
    goBuy: function (groupId, collageId) {
      if (this.testInfo.collage.userType != -1 && this.testInfo.collage.groupId != groupId) {
        this.$showCjToast({
          text: '您已在拼团中，不需要再去拼单啦！',
          type: 'warn'
        });
      } else {
        if (this.testInfo.collage.status == 1) {
          this.$showCjToast({
            text: '活动未开始，暂不能拼团！',
            type: 'warn'
          });
        } else {
          //要加判断是否选择阶梯
          if (this.testInfo.collage && this.testInfo.collage.collageGroupType == 1 ) {
            this.$refs.collageGrades.goChoseBuy()
          } else {
            this.$refs.collageGrades.showBuy()
            // this.isShowBuy = true; //选择阶梯
          }
        }
      }
    },
    //点击立即购买
    clickBuy() {
      if (this.bindPhoneSetting && this.bindPhoneSetting.buyBind) {
        if (utilJs.goBindMobile()) return;
      }
      if (this.testInfo.isRelForm == true && this.testInfo.hasFormLog == false && localStorage.getItem("showForm") == 1) {
        this.goForm('');
        return;
      }
      let queryT = null;
      queryT = {
        extId: this.testInfo.libraryId,
        ckFrom: this.cfrom.itemBank,
        isFromInvite: 0,
        cId: -1,
      }
      if (this.testInfo.sales && this.testInfo.sales.sales.status == 2 && this.optimal && this.optimal.optimalPriceType == 101) {
        queryT.pId = this.testInfo.sales.pId;
      }
      this.$routerGo(this, "push", {
        path: "/homePage/course/coursePay",
        query: queryT
      });
    },
    wechatShare: function () {
      let title = this.testInfo.name;
      let shareImg = this.testInfo.sales ? this.testInfo.sales.shareImg : this.testInfo.avatar;
      if (this.testInfo.collage != null && (this.testInfo.collage.status == 2 || this.testInfo.collage.status == 1)) {
        title = `【邀您一起拼团】${title}`;
      }
      if (this.testInfo.sales) {
        title = `【限时抢购】${title}`;
      }
      if (this.testInfo.bargain != null && ((this.testInfo.bargain.status == 1 && this.testInfo.bargain.isPreheat == 1) || this.testInfo.bargain.status == 2)) {
        title = `【邀您一起砍价】${title}`;
      }
      let shareUrl =
        window.location.href.split("#")[0] +
        "#/homePage/itemBank/questionSaleDetail?libraryId=" +
        this.libraryId + "&refereeId=" +
        localStorage.getItem("userId");
      let shareDesc = this.testInfo.desc || "点击查看详情";
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () {});
    },
    //手机端分享
    appShare: function () {
      var title = this.testInfo.name;
      var shareImg = this.testInfo.sales ? this.testInfo.sales.shareImg : this.testInfo.avatar;
      if (this.testInfo.collage != null && (this.testInfo.collage.status == 2 || this.testInfo.collage.status == 1)) {
        title = `【邀您一起拼团】${title}`;
      }
      if (this.testInfo.sales) {
        title = `【限时抢购】${title}`;
      }
      if (this.testInfo.bargain != null && ((this.testInfo.bargain.status == 1 && this.testInfo.bargain.isPreheat == 1) || this.testInfo.bargain.status == 2)) {
        title = `【邀您一起砍价】${title}`;
      }
      var shareUrl =
        window.location.href.split("#")[0] +
        "#/homePage/itemBank/questionSaleDetail?libraryId=" +
        this.libraryId + "&refereeId=" +
        localStorage.getItem("userId");
      var shareDesc = this.testInfo.desc || "点击查看详情";
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    },
  },
  activated() {
    setDocumentTitle("练习详情"); // eslint-disable-line
    this.libraryId = this.$route.query.libraryId;
    this.ttId = this.$route.query.ttId || "";
    this.tpId = this.$route.query.tpId || ""; //环节id
    this.tlId = this.$route.query.tlId || "";
    this.themeId = this.$route.query.themeId || '';
    this.progress = this.$route.query.progress || "";
    this.comboId = this.$route.query.comboId
    this.isiOS = navigator.userAgent.indexOf("IOSLogin") > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1;
    this.testInfo = {};
    this.couponList = [];
    this.couponPage = 1;
    this.couponLoading = false;
    this.couponIsPage = false;
    this.optimal = null;
    getBindPhoneSetting(global.ckFrom.itemBank).then(res => {
      this.bindPhoneSetting = res;
    });
    this.getTestDetail();
    this.getCouponList();
  },
  deactivated() {
  }
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only  -->
<style scoped>
.tinymce-text{
  color: #666;
}
.tinymce-text >>> a > img {
  pointer-events: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.closeBig >>> p > img,
.closeBig >>> section > img,
.closeBig >>> div > img,
.closeBig >>> img {
  pointer-events: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.aCloseBig >>> p > a > img,
.aCloseBig >>> section > a > img,
.aCloseBig >>> div > a > img {
  pointer-events: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.tabhBar {
  width: 100%;
  max-width: 16rem;
  position: fixed;
  top: 1.7rem;
  left: 0;
  right: 0;
  margin: auto;
  background-color: #fff;
  z-index: 900;
}
.tab-bar-ios {
  width: 100%;
  max-width: 16rem;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  margin: auto;
  background-color: #fff;
  z-index: 9999;
}
</style>
